// =====================================================================
//
//  This file is part of the Microsoft Dynamics CRM SDK code samples.
//
//  Copyright (C) Microsoft Corporation.  All rights reserved.
//
//  This source code is intended only as a supplement to Microsoft
//  Development Tools and/or on-line documentation.  See these other
//  materials for detailed information regarding Microsoft code samples.
//
//  THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
//  KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//  IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//  PARTICULAR PURPOSE.
//
// =====================================================================
using System;
using System.Reflection;

namespace Microsoft.Xrm.Sdk
{
	/// <summary>
	/// Type class related extension methods and utilities.
	/// </summary>
	/// <exclude/>
	internal static class TypeExtensions
	{
		/// <summary>
		/// Retrieves the underlying type if the type is nullable, otherwise returns the current type.
		/// </summary>
		/// <param name="type"></param>
		/// <returns></returns>
		public static Type GetUnderlyingType(this Type type)
		{
			return Nullable.GetUnderlyingType(type) ?? type;
		}

		/// <summary>
		/// Determines if a generic type is assignable from this type.
		/// </summary>
		/// <typeparam name="T"></typeparam>
		/// <param name="type"></param>
		/// <returns></returns>
		public static bool IsA<T>(this Type type)
		{
			return IsA(type, typeof(T));
		}

		/// <summary>
		/// Determines if the input reference type is assignable from this type.
		/// </summary>
		/// <param name="type"></param>
		/// <param name="referenceType"></param>
		/// <returns></returns>
		public static bool IsA(this Type type, Type referenceType)
        {
#if SILVERLIGHT
			return referenceType != null ? referenceType.IsAssignableFrom(type) : false;
#else
            return referenceType != null ? referenceType.GetTypeInfo().IsAssignableFrom(type.GetTypeInfo()) : false;
#endif
        }
	}
}
